package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.sun.xml.internal.bind.v2.TODO;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
   private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;


  private static  final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    private boolean trylock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MINUTES);

        return BooleanUtil.isTrue(flag);
    }
private void unlock(String key){
        stringRedisTemplate.delete(key);
}
    @Override
    public Result queryById(Long id) {
  //1.缓存穿透
  //      Shop shop = queryWithPassThrough(id);
        //2.缓存击穿 问题 互斥锁解决缓冲击穿问题
      //  Shop shop = queryWithMutex(id);
        //3.逻辑过期解决缓存击穿问题
       // Shop shop = queryWithLogicalExpire(id);
        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY+id,id, Shop.class,
                this::getById,RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES); //解决缓存穿透
         ///// this::getById == (id)->{id}
        if (shop==null){
            return Result.fail("店铺不存在");
        }
        return  Result.ok(shop);

    }
    public Shop  queryWithLogicalExpire(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY+id;
        //先从redis查询缓存
        String shopjson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        System.out.println(shopjson);
        if(StrUtil.isBlank(shopjson)){
            //未命中返回null

            return null;


        }
        //命中 需要先把json反序列化
      RedisData redisData =  JSONUtil.toBean(shopjson,RedisData.class);
       JSONObject data = (JSONObject)redisData.getData();
       Shop shop = JSONUtil.toBean(data,Shop.class);
       LocalDateTime expireTime = redisData.getExpireTime();

        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            return shop;
            //没有过期返回店铺信息
        }

        //缓存重建
        // 1 互斥锁
        String lockkey = RedisConstants.LOCK_SHOP_KEY + id ;
        Boolean islock = trylock(lockkey);
        //是否锁成功
        if (islock){
           String doublecheck = stringRedisTemplate.opsForValue().get(key);
           //二次校验
            try {
                if (doublecheck != null ){
                    //开启独立线程
                    //TODO 开启独立线程 实现缓存重建
                    CACHE_REBUILD_EXECUTOR.submit(()->{
                        this.saveShop2Redis(id,20L);

                    });
                }
            } finally {
                unlock(lockkey);
            }

        }

        //失败 返回过期商户信息
        return  shop;



    }
    public Shop queryWithMutex(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY+id;
        //先从redis查询缓存
        String shopjson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在

        if(StrUtil.isNotBlank(shopjson)){


            return JSONUtil.toBean(shopjson,Shop.class);

//            存在返回
        }
        if (shopjson != null){
            return null;
        }
        //4.1 缓存击穿
        String lockkey = RedisConstants.LOCK_SHOP_KEY + id ;
        Shop shop = null;
        try {
            boolean islock = trylock(lockkey);
            if (!islock){
                Thread.sleep(50);
                return queryWithMutex(id);
            }
//        //二次判断  检测redis缓存是否存在
//
//          String shopjson1 = stringRedisTemplate.opsForValue().get(key);
//          //判断是否存在
//          System.out.println(shopjson1);
//          if(StrUtil.isNotBlank(shopjson1)){
//
//
//              return JSONUtil.toBean(shopjson1,Shop.class);
//                }
////            存在返回
//
//

            //不存在 查询数据库
            shop = getById(id);
            Thread.sleep(200);
            //数据库不存在 返回错误
            if(shop == null ){

                stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //存在数据库 写入数据到Redis
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {//释放锁
            unlock(lockkey);
        }


        //返回
        return shop;



    }
    public Shop  queryWithPassThrough(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY+id;
        //先从redis查询缓存
        String shopjson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        System.out.println(shopjson);
        if(StrUtil.isNotBlank(shopjson)){


            return JSONUtil.toBean(shopjson,Shop.class);

//            存在返回
        }
        if (shopjson != null){
            return null;
        }

        //不存在 查询数据库
        Shop shop = getById(id);
        //数据库不存在 返回错误
        if(shop == null ){

            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //存在数据库 写入数据到Redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //返回
        return shop;
    }
    public void saveShop2Redis(Long id, Long expireSeconds){
        Shop shop = getById(id);
        RedisData redisData = new RedisData() ;
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));

    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null ){
            return Result.fail("店铺ID不能为空");

        }
        updateById(shop);
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1 是否需要根据坐标查询
        if (x == null || y  == null){ //2 分页查询
            Page<Shop> page = query().eq("type_id",typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //3 查询redis 按照距离排序，分页. shopId distance
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE; // 计算分页参数
        String key ="shop:geo:"+ typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key, GeoReference.fromCoordinate(x, y), new Distance(5000)
                , RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));


        //4 解析ID  根据ID查询店铺
        if (results == null ){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from){
            return  Result.ok();
        }
        ArrayList<Long> ids = new ArrayList<>(list.size());
        HashMap<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr,distance
            );
        });
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
